﻿using OrBitDataModule;
using OrBitDataModule.Adaptor;
using OrBitDataModule.Base;
using OrBitDataModule.Common;
using OrBitDataModule.Interface;
using OrBitDataModule.Models;
using OrBitDataScript;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Scripter
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            StartService service = new StartService();
            Application.Run();
        }
    }
    internal class StartService
    {
        TaskService Service = null;
        string UniqueId = string.Empty;
        string UserName = string.Empty;
        string Password = string.Empty;
        public StartService()
        {
            Service = new TaskService();
            ReadParameters();
            Start();
        }


        ~StartService() { Stop(); Application.Exit(); }
        private async void Start()
        {
            List<TaskModel> list = await Service.InitAllTask();
            TaskModel taskModel = Service.GetTaskModel(list, UniqueId);
            if (taskModel != null)
            {
                taskModel.DataTask.IsScripDebug = true;
                Script script = new Script();
                IContext context = new Context(taskModel.DataTask);
                script.GetType().BaseType.InvokeMember("Init", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, script, new object[] { context });
                taskModel.DataTask.Script = script;
                Service.StartTask(UniqueId);
            }

        }

        private void Stop()
        {
            Service.StopTask(UniqueId);
        }
        private void ReadParameters()
        {
            string text = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "params.conf"));
            UniqueId = GetValueAfterEqualSign(text, "UniqueId");
            UserName = GetValueAfterEqualSign(text, "UserName");
            Password = GetValueAfterEqualSign(text, "Password");
            SharedData.LoginUserPassword = Password;
            SharedData.LoginUserName = UserName;
            File.Delete(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "params.conf"));
        }
        string GetValueAfterEqualSign(string input, string key)
        {
            int startIndex = input.IndexOf(key + " = ") + (key + " = ").Length;
            int endIndex = input.IndexOf("\n", startIndex);

            if (endIndex == -1)
            {
                endIndex = input.Length;
            }

            return input.Substring(startIndex, endIndex - startIndex).Trim();
        }
    }
}
